﻿package cn.antscript.autoView.detector 
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.media.Camera;
	import flash.media.Video;
	import jp.maaash.ObjectDetection.ObjectDetector;
	import jp.maaash.ObjectDetection.ObjectDetectorEvent;
	import jp.maaash.ObjectDetection.ObjectDetectorOptions;
	
	/**
	 * ...
	 * @author AntScript
     * @blog  http://www.antscript.cn
	 */
	public class Detector extends Sprite
	{
		private static const _cameraWidth:int = 640;
		private static const _cameraHeight:int = 480;
		private static const _cameraFPS:int = 10;
		
		private var _detector:ObjectDetector;
		private var _options:ObjectDetectorOptions;
		private var _detectorBitmap:Bitmap;
		
		private var _video:Video;
		
		public function Detector() 
		{
			initDetector();
			
		}
		private function initDetector():void
		{
			_detector = new ObjectDetector();
			_detector.options = getDetectorOptions();
			_detector.loadHaarCascades( "../lib/face.zip" );	
			_detector.addEventListener(ObjectDetectorEvent.HAARCASCADES_LOAD_COMPLETE, onXMLLoaded);
		}
		
		private function onXMLLoaded(e:ObjectDetectorEvent):void 
		{
			initCamera();
			
			_detector.addEventListener(ObjectDetectorEvent.DETECTION_COMPLETE, onDetectionCom);
			addEventListener(Event.ENTER_FRAME, onE);
		}
		
		private function onE(e:Event):void 
		{
			_detectorBitmap = new Bitmap( new BitmapData( _video.width, _video.height, false ) );
			_detectorBitmap.bitmapData.draw( _video );
			_detector.detect( _detectorBitmap );
		}
		
		private function onDetectionCom(e:ObjectDetectorEvent):void 
		{
			if (e.rects.length == 0) return;
			
			trace(e.rects)
		}
		private function getDetectorOptions () : ObjectDetectorOptions {
			
			_options = new ObjectDetectorOptions();
			_options.min_size = 50;
			_options.startx = ObjectDetectorOptions.INVALID_POS;
			_options.starty = ObjectDetectorOptions.INVALID_POS;
			_options.endx = ObjectDetectorOptions.INVALID_POS;
			_options.endy = ObjectDetectorOptions.INVALID_POS;
			return _options;
			
		}
		
		private function initCamera():void
		{
			var camera:Camera = Camera.getCamera();
			
			if (camera) {
				camera.setMode(_cameraWidth, _cameraHeight, _cameraFPS);
				_video = new Video(_cameraWidth, _cameraHeight);
				_video.attachCamera(camera);
				addChild(_video);
			}
			
			
		}
	}
	
}